/*
 *    Copyright © OpenAtom Foundation.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package com.inspur.edp.bef.builtincomponents.FKConstraints;

import com.inspur.edp.bef.api.BefRtBeanUtil;
import com.inspur.edp.bef.core.scope.SingleBETypeExtension;
import com.inspur.edp.cef.api.RefObject;
import com.inspur.edp.cef.api.message.BizMessage;
import com.inspur.edp.cef.api.message.IBizMessage;
import com.inspur.edp.cef.api.message.MessageLevel;
import com.inspur.edp.cef.api.message.MessageLocation;
import com.inspur.edp.cef.api.scope.ICefScopeNodeParameter;
import com.inspur.edp.cef.core.i18n.I18nResourceUtil;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

public class FKConstraintValScopeExtension extends SingleBETypeExtension {

  @Override
  public void onExtendSetComplete() {
    Map<String, Map<String, FKConstriantValItem>> items = new HashMap<>();
    for (ICefScopeNodeParameter parameter : super.getParameters()) {
      addParamToItems(items, (FKConstraintValidateParam) parameter);
    }

    checkFKConstraintByDac(items);
  }

  private void addParamToItems(Map<String, Map<String, FKConstriantValItem>> items,
      FKConstraintValidateParam parameter) {
    List<String> nodeItems;
    String nodeCode = parameter.getNodeCode();
    String propName = parameter.getPropName();
    Map<String, FKConstriantValItem> nodeItems1;
    if (items.containsKey(nodeCode) == false) {
      nodeItems1 = new HashMap<>();
      items.put(nodeCode, nodeItems1);
    } else {
      nodeItems1 = items.get(nodeCode);
    }
    if (nodeItems1.containsKey(propName)) {
      nodeItems = nodeItems1.get(propName).getDataIds();
    } else {
      List<String> list = new ArrayList<>();
      FKConstriantValItem valItem = new FKConstriantValItem(parameter.getBefConfig(), list,
              parameter.getTargetNodeCode(), parameter.getSourcePropName());
      valItem.getSourceDataIds().add(parameter.getBENodeContext().getID());
      nodeItems1.put(propName, valItem);
      nodeItems = list;
    }

    if (nodeItems.contains(parameter.getDataId())) {
      return;
    }
    nodeItems.add(parameter.getDataId());
  }

  private void checkFKConstraintByDac(Map<String, Map<String, FKConstriantValItem>> items) {
    if (items.size() == 0) {
      return;
    }
    for (Map.Entry<String, Map<String, FKConstriantValItem>> nodeItems : items.entrySet()) {
      checkNodeFKConstraint(nodeItems);
    }
  }

  private void checkNodeFKConstraint(Entry<String, Map<String, FKConstriantValItem>> nodeItems) {
    if (nodeItems.getValue() == null || nodeItems.getValue().size() == 0) {
      return;
    }
    for (Map.Entry<String, FKConstriantValItem> propItem : nodeItems.getValue().entrySet()) {
      checkPropFKConstraint(nodeItems.getKey(), propItem);
    }
  }

  private void checkPropFKConstraint(String nodeCode, Entry<String, FKConstriantValItem> propItem) {
    if (propItem.getValue() == null || propItem.getValue().getDataIds() == null
        || propItem.getValue().getDataIds().size() == 0) {
      return;
    }
    String befConfig = propItem.getValue().getBefConfig();
    RefObject<List<String>> noneEffectiveIds = new RefObject<>(new ArrayList<>());
    boolean isEffective = true;
    if(propItem.getValue().getPropName() == null || propItem.getValue().getPropName().isEmpty() ){
      isEffective = BefRtBeanUtil.getLcpFactory().createLcp(befConfig)
              .isDatasEffective(propItem.getValue().getTargetNodeCode(), propItem.getValue().getDataIds(),
                      noneEffectiveIds);
    }
    else {
      isEffective = BefRtBeanUtil.getLcpFactory().createLcp(befConfig)
              .isDatasEffective(propItem.getValue().getTargetNodeCode(), propItem.getValue().getPropName(), propItem.getValue().getDataIds(),
                      noneEffectiveIds);
    }
    if (isEffective) {
      return;
    }

    String exceptionCode = I18nResourceUtil
        .getResourceItemValue("pfcommon", "cef_exception.properties", "Gsp_Bef_FKVal_0001");
    if(!(propItem.getValue().getPropName() == null || propItem.getValue().getPropName().isEmpty()) ){
      exceptionCode = exceptionCode.replace("ID", propItem.getValue().getPropName());
    }
    exceptionCode += noneEffectiveIds.argvalue.get(0);
    String propDisplayName = getSessionItem().getBEManager().getModelInfo()
        .getCustomResource(nodeCode).getPropertyDispalyName(propItem.getKey());

    IBizMessage message = createMessage(nodeCode, propItem.getKey(),
        propDisplayName + exceptionCode,
        propItem.getValue().getSourceDataIds());
    addMessage(message);
    //throw new BefException(ErrorCodes.ForeignKey, propDisplayName + exceptionCode, null, ExceptionLevel.Warning);
  }

  public IBizMessage createMessage(String nodeCode, String propName, String msg, List<String> ids) {
    return new BizMessage() {{
      setMessageFormat(msg);
      setLevel(MessageLevel.Error);
      setLocation(new MessageLocation() {{
        setDataIds(ids);
        setNodeCode(nodeCode);
        setColumnNames(Arrays.asList(propName));
      }});
    }};
  }
}
